export const useUserStore = defineStore('sUser', () => {
  // 用户信息
  let user = $ref({})
  let customerInfo = $ref({})
  let userRoleList = $ref([])
  // 我的店铺信息
  let myShopList = $ref([])
  // 菜单权限标识
  const MENU_POLICY_ACT = 'menu:read'
  const PAGE_POLICY_ACT = 'pageAct'
  let userMenus = $ref([])
  let sysMenus = $ref([])
  let companyMenus = $ref([])
  let pageAuth = $ref({
    // 'fullPath': {'comp_code':true}
  })

  // 获取系统所有菜单
  const getSysMenu = async () => {
    const { status, data } = await Fetch('/api/s/t/site_menu', {
      headers: { timestamp: Date.now() },
      data: { limit: 1000, category: 'pc', is_show: 1, is_deleted: 0 },
    })
    if (status !== 200 || data.code !== 0) {
      message.error(data?.msg)
      return
    }
    sysMenus = data.result.dataList
  }

  // 侧栏菜单状态
  let currMenuId = $ref('')
  const setMenu = (id) => {
    currMenuId = id
  }
  let openedDirIds = $ref([])
  const setOpenDir = (payload) => {
    const idx = openedDirIds.findIndex(e => e === payload)
    if (idx > -1) {
      openedDirIds.splice(idx, 1)
    } else {
      openedDirIds.push(payload)
    }
  }

  const { tokenCompanyCode } = $(useLoginStore())
  const currRoles = computed(() => {
    if (isNilOrEmpty(userRoleList)) { return [] }
    return userRoleList.filter(e => e.company_code === tokenCompanyCode)
  })
  // 获取新角色监听
  watch(currRoles, val => {
    if (isNotNilOrEmpty(val.value)) {
      getUserMenus()
    }
  })
  // 是否管理员
  const isAdmin = computed(() => {
    return user.id === '1'
  })
  // 查询按钮(模块)权限
  const hasAuth = computed(() => (comp_code) => {
    if (isAdmin.value) { return true }
    // const route = useRoute()
    // if (!has(pageAuth, route.fullPath)) { return false }
    // if (!has(pageAuth[route.fullPath], comp_code)) { return false }
    return pageAuth[route.fullPath][comp_code]
  })
  // 更新当前用户信息
  const updateUserInfo = async (customerId) => {
    const result = await Fetch(`shopping/login/getUserInfo`)
    console.log(result.data.code == 200,result.data.code, 'asdsadas');
    if (result.data.code == 200) {
      console.log('?????????');

      user = result.data.data
      getCustomerInfo(user.customerId)
      return true
    } else {
      // uni.showToast({
      //   title: result?.data?.msg || '获取用户信息失败',
      //   icon: 'none'
      // })
      uni.clearStorageSync()
      return false
    }

  }

  // 会员信息
  const getCustomerInfo = async (customerId) => {
    const result = await Fetch(`shopping/customerInfo/${customerId}`)
    console.log(result, 'asdsadas');
    customerInfo = result.data.data
  }

  // 获取自己店铺信息
  const getMyShopInfo = async () => {
    try {
      // 先尝试从缓存加载
      const cachedData = uni.getStorageSync('my-shop-list-cache')
      if (cachedData) {
        myShopList = JSON.parse(cachedData)
        console.log('从缓存加载店铺数据:', myShopList)
      }

      // 然后发起网络请求更新数据
      const res = await Fetch('shopping/shopInfo/getMyInfo', {
        method: 'get',
      })

      if (res.data.code === 200) {
        console.log(res.data.data, 'res.data.data')
        myShopList = res.data.data

        // 存储到本地缓存
        uni.setStorageSync('my-shop-list-cache', JSON.stringify(res.data.data))
        console.log(myShopList, 'myShopList 已更新并缓存')
      }
    } catch (error) {
      console.error('获取店铺信息失败:', error)

      // 如果网络请求失败但有缓存数据，使用缓存
      const cachedData = uni.getStorageSync('my-shop-list-cache')
      if (cachedData && !myShopList.length) {
        myShopList = JSON.parse(cachedData)
        console.log('网络请求失败，使用缓存数据')
      }
    }
  }


  const clearUser = () => {
    user = {}
    customerInfo = {}
    currMenuId = ''
    openedDirIds = []
    userRoleList = []
    pageAuth = {}
    sysMenus = []
    userMenus = []
    companyMenus = []
    pageAuth = {}
    hrRosterList.value = []
  }
  // 获取花名册
  const getHrRoster = async (formData = {}, methodType = 'get') => {
    const { status, data } = await Fetch('/api/s/t/hr_roster', {
      method: methodType,
      headers: { timestamp: Date.now() },
      data: objectNilClean(formData),
    })
    if (status !== 200 || data.code !== 0) { return null }
    return { status, data }
  }
  // start 花名册缓存
  const hrRosterList = ref([])
  const getHrRosterCache = async (refresh = false) => {
    if (refresh) {
      hrRosterList.value = []
    }
    if (isNilOrEmpty(hrRosterList.value)) {
      const _rosterList = await getHrRoster({ limit: 5000 }, 'POST')
      if (isNotNilOrEmpty(_rosterList)) {
        hrRosterList.value = _rosterList.data.result.dataList
      }
    }
  }
  // end 花名册缓存

  // 获取当前用户权限可以查询的花名册
  let userRoster = $ref([])
  const getUserRoster = async () => {
    const { status, data } = await Fetch('/api/s/t/hr_roster', {
      headers: { timestamp: Date.now() },
      // TODO: 根据权限获取 更新接口
    })
    if (status !== 200 || data.code !== 0) {
      return
    }
    userRoster = data.result.dataList
  }
  // 获取当前公司角色所有菜单
  const getUserMenus = async () => {
    userMenus = []
    const { status, data } = await Fetch('/api/casbin/getRolesObjs', { method: 'post', data: { roles: currRoles.value.map(e => e.id), act: MENU_POLICY_ACT } })
    if (status !== 200 || data.code !== 0) { return }
    if (isNotNilOrEmpty(data.result)) {
      userMenus = data.result
    }
  }

  const { hasPolices } = useAuthStore()
  // 页面权限
  const getPageAuthList = async () => {
    const route = useRoute()
    const { status, data } = await Fetch('/api/s/t/site_menu_component', { method: 'post', data: { menu_path: route.fullPath } })
    if (status !== 200 || data.code !== 0) { return [] }
    if (isNotNilOrEmpty(data.result?.dataList)) {
      const payload = []
      data.result.dataList.forEach(e => {
        currRoles.value.forEach(v => {
          payload.push({ sub: v.id, obj: e.id, act: e.comp_code })
        })
      })
      const authList = await hasPolices(payload)
      if (isNilOrEmpty(authList?.result)) { return }
      authList.result.forEach(e => {
        if (!has(pageAuth, route.fullPath)) {
          pageAuth[route.fullPath] = {}
        }
        if (!has(pageAuth[route.fullPath], e.act)) {
          pageAuth[route.fullPath][e.act] = {}
        }
        if (!has(pageAuth[route.fullPath][e.act], e.hasPolicy)) {
          pageAuth[route.fullPath][e.act] = e.hasPolicy
        } else if (!pageAuth[route.fullPath][e.act][e.hasPolicy]) {
          pageAuth[route.fullPath][e.act] = e.hasPolicy
        }
      })
    }
  }

  return {
    MENU_POLICY_ACT,
    PAGE_POLICY_ACT,
    userMenus: $$(userMenus),
    sysMenus: $$(sysMenus),
    companyMenus: $$(companyMenus),
    user: $$(user),
    customerInfo: $$(customerInfo),
    userRoleList: $$(userRoleList),
    myShopList: $$(myShopList),
    currRoles,
    isAdmin,
    currMenuId: $$(currMenuId),
    openedDirIds: $$(openedDirIds),
    userRoster: $$(userRoster),
    updateUserInfo,
    getMyShopInfo,
    getCustomerInfo,
    clearUser,
    setMenu,
    setOpenDir,
    getSysMenu,
    getPageAuthList,
    getHrRoster,
    getUserRoster,
    hasAuth,
    hrRosterList,
    getHrRosterCache,
  }
}, { unistorage: { key: 'config-user' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
